/*
 * www.7yangche.com Inc.
 * Copyright (c) 2014 All Rights Reserved.
 */
package com.catena.core.inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;

/**
 * @author cyzhang
 * @extend hx
 */
public class InjectionContext {

    private static final Logger LOGGER = LoggerFactory.getLogger(InjectionContext.class);
    private static final String ERROR = "动态抓取Bean失败，ApplicationContext，没有被初始化";
    private static ApplicationContext applicationContext;

    private InjectionContext() {
    }

    private static AutowireCapableBeanFactory getAutowireCapableBeanFactory() {
        return InjectionContext.getApplicationContext().getAutowireCapableBeanFactory();
    }

    private static ApplicationContext getApplicationContext() {
        return InjectionContext.applicationContext;
    }

    public static void loadApplicationContext(ApplicationContext applicationContext) {
        InjectionContext.applicationContext = applicationContext;
    }

    public static void autowireBean(Object target) {
        if (InjectionContext.getApplicationContext() == null) {
            LOGGER.error("自动注入失败，ApplicationContext，没有被初始化");
            return;
        }
        InjectionContext.getAutowireCapableBeanFactory().autowireBean(target);
    }

    public static <T> T getBean(Class<T> targetType) {
        if (InjectionContext.getApplicationContext() == null) {
            LOGGER.error(ERROR);
            return null;
        } else {
            return InjectionContext.getApplicationContext().getBean(targetType);
        }
    }

    public static <T> T getBean(Class<T> targetType, String qualifier) {
        if (InjectionContext.getApplicationContext() == null) {
            LOGGER.error(ERROR);
            return null;
        } else {
            return InjectionContext.getApplicationContext().getBean(qualifier, targetType);
        }
    }
}
